<template>
  <div class="box8">
    <div class="title">
      <p>机器人状态</p>
    </div>
    <div class="charts" ref="charts"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { ref, watch, nextTick } from "vue";
import { RobotApi } from "@/api/map/typecount";

/* 1. 接收城市名 */
const props = defineProps<{ city: string }>();

/* 2. DOM */
const charts = ref<HTMLDivElement>();
let myChart: echarts.ECharts;

/* 3. 绘图函数 */
async function drawPie() {
  const res = await RobotApi.getRobotTypeCount({ province: props.city });
  const data1 = res.map((i) => i.name);
  const data2 = res.map((i) => ({ name: i.name, value: i.num }));

  const colorList = [
    { c1: "#ECE833", c2: "#ECE833" },
    { c1: "#FC9424", c2: "#FC9424" },
    { c1: "#23C6D5", c2: "#23C6D5" },
    { c1: "#2986F7", c2: "#2986F7" },
    { c1: "#B06DF6", c2: "#B06DF6" },
  ];

  const option: echarts.EChartsOption = {
    legend: {
      orient: "vertical",
      left: "58%",
      top: "30%",
      itemWidth: 8.5,
      itemHeight: 8.5,
      icon: "rect",
      itemGap: 25,
      textStyle: { color: "#fff" },
      formatter: (name: string) => {
        const tar = data2.find((i) => i.name === name)!;
        return `   ${name}     ${tar.value}`;
      },
      data: data1,
    },
    series: [
      {
        name: "机器人统计",
        type: "pie",
        radius: ["50%"],
        center: ["35%", "45%"],
        startAngle: 90,
        avoidLabelOverlap: false,
        label: { show: false },
        data: data2,
        itemStyle: {
          color: (param: any) =>
            new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: colorList[param.dataIndex].c1 },
              { offset: 1, color: colorList[param.dataIndex].c2 },
            ]),
        },
      },
    ],
  };

  if (!myChart) myChart = echarts.init(charts.value!);
  myChart.setOption(option, true);
}

/* 4. 首次 + 城市变化立即重画 */
nextTick(drawPie);
watch(() => props.city, drawPie);
</script>

<style scoped lang="scss">
.box8 {
  width: 100%;
  height: 300px;
  border-bottom: 1px solid #ccc;
  // background-color: aquamarine;
  .title {
    position: absolute;
    top: 35%;
    left: 0%;
    letter-spacing: 8px; /* 设置字间距 */
    writing-mode: vertical-rl;
    p {
      color: white;
      font-size: 14px;
    }
  }

  .charts {
    height: 100%;
  }
}
</style>
